package com.key;

import java.util.List;
import java.util.Stack;
import java.util.Timer;
import java.util.TimerTask;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import com.key.util.ChessMove;
import com.key.util.ChessPoint;
import com.key.util.GameParams;
import com.key.util.KeyChineseChessRule;
import com.key.util.KeyScore;
import com.key.util.UserSystemData;
import com.key.util.Util;

public class KeyChineseChessView extends View {

	public static int screenWidth;//屏幕宽度
	public static int screenHeight;//屏幕高度
	private float scaleX = 1;//宽压缩比例
	private float scaleY = 1;//高压缩比例
	private Paint paint = new Paint();//paint
	public static Stack<ChessMove> moveStack = new Stack<ChessMove>();//棋子移动记录

	public static float chessY = (float) 115.5;//左上棋子坐标Y
	public static float chessX = (float) 22.5;//左上棋子X

	public static float chessLength = (float) 39.7;//棋盘格子长度
	public static float chessLX = 15;// 棋子半宽
	public static float chessLY = 15;// 棋子半高

	public final static int NOCHESS = 0; // 无棋子
	public final static int B_KING = 1; // 黑将
	public final static int B_CAR = 2; // 黑车
	public final static int B_HORSE = 3; // 黑马
	public final static int B_CANON = 4; // 黑炮
	public final static int B_BISHOP = 5; // 黑士
	public final static int B_ELEPHANT = 6; // 黑象
	public final static int B_PAWN = 7; // 黑卒
	public final static int B_BEGIN = B_KING; //黑棋开始大小
	public final static int B_END = B_PAWN;	//黑色结束大小

	public final static int R_KING = 8; // 红帅
	public final static int R_CAR = 9; // 红车
	public final static int R_HORSE = 10; // 红马
	public final static int R_CANON = 11; // 红炮
	public final static int R_BISHOP = 12; // 红士
	public final static int R_ELEPHANT = 13; // 红象
	public final static int R_PAWN = 14; // 红兵
	public final static int R_BEGIN = R_KING; //红棋开始
	public final static int R_END = R_PAWN; //红棋结束

	//棋子bitmap
	private Bitmap imgBkingNew;
	private Bitmap imgBbishopNew;
	private Bitmap imgBelephantNew;
	private Bitmap imgBhorseNew;
	private Bitmap imgBrookNew;
	private Bitmap imgBcannonNew;
	private Bitmap imgBpawnNew;
	private Bitmap imgRkingNew;
	private Bitmap imgRbishopNew;
	private Bitmap imgRelephantNew;
	private Bitmap imgRhorseNew;
	private Bitmap imgRrookNew;
	private Bitmap imgRcannonNew;
	private Bitmap imgRpawnNew;

	//移动棋子后的背景
	private Bitmap imgRbgNew;
	private Bitmap imgBbgNew;

	private boolean isPoint = false;//是否已选择要移动的棋子
	private int px = -99;//已选择棋子的x
	private int py = -99;//已选择棋子的y
	public static boolean rsel = false;//红棋是否已动
	public static boolean bsel = false;//黑棋是否已动
	private ChessMove rMove = new ChessMove();//红棋移动
	private ChessMove bMove = new ChessMove();//黑棋移动
	public static boolean isThinking = false;//程序是否在思考

	private KeyChineseChessRule keyChineseChessRule = new KeyChineseChessRule();//检查规则类
	private boolean isAntRule = false;//是否违反了规则
	private ChessMove ruleChessMove = new ChessMove();//将要违反规则的移动

	//压缩matrix
	private Matrix matrix = new Matrix();

	/**
	 * 点击棋盘
	 */
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		if (GameParams.isGameStart) {
			float x = event.getX();
			float y = event.getY();
			// 点击位置在棋盘内
			if (x >= chessX * scaleX - chessLX
					&& x <= chessX * scaleX + 8 * chessLength * scaleX
							+ chessLX) {
				if (y >= chessY * scaleY - chessLY
						&& y <= chessY * scaleY + 9 * chessLength * scaleY
								+ chessLY) {
					// 点击的坐标
					int cX = (int) (x - chessX * scaleX + chessLX)
							/ (int) (chessLength * scaleX);
					int cY = (int) (y - chessY * scaleY + chessLY)
							/ (int) (chessLength * scaleY);
					if (isPoint) {
						// 点击的棋子仍为红棋，切换棋子
						if (position[cY][cX] > 7) {
							px = cX;
							py = cY;
							GameParams.chessAudio
									.playRaw(GameParams.soundCapture);
							invalidate();
						} else if (Util.isMoveRule(py, px, cY, cX)) {
							//移动是否符合移动规则
							isPoint = false;
							playMoveAnimation(px, cX, py, cY);//播放移动动画
							// 红棋移动类
							rMove = new ChessMove();
							rMove.from.x = py;
							rMove.from.y = px;
							rMove.to.x = cY;
							rMove.to.y = cX;
							rMove.chessFrom = position[py][px];
							rMove.chessTo = position[cY][cX];
							moveStack.push(rMove);//记录移动
							rsel = true;//红棋已移动
							position[cY][cX] = position[py][px];
							position[py][px] = NOCHESS;

							//检查是否长将
							if (keyChineseChessRule.checkIsKillUtil(position)) {
								isAntRule = true;
								keyChineseChessRule.listPosition.add(position);
							}
							//检查是否吃子，吃子播放吃子音效
							if (Util.isEatChess(rMove)) {
								GameParams.chessAudio
										.playRaw(GameParams.soundEat);
							} else {
								GameParams.chessAudio
										.playRaw(GameParams.soundMove);
							}
							//检查是否分数胜负
							int whoIswin = -99;
							whoIswin = Util.whoIsSuccess();
							//红棋获胜
							if (whoIswin == 1) {
								KeyChineseChessActivity.imgVRedLive
										.setVisibility(View.VISIBLE);
								GameParams.chessAudio
										.playRaw(GameParams.soundWin);
								invalidate();
								caculateWinScore();
								GameParams.singleGameActivity.initView();
								GameParams.isGameStart = false;
								exitGameBoard();
								return super.onTouchEvent(event);
							} else if (whoIswin == 99) {
								//和棋
								KeyChineseChessActivity.imgVAllLive
										.setVisibility(View.VISIBLE);
								invalidate();
								GameParams.isGameStart = false;
								return super.onTouchEvent(event);
							}
							// 将军
							if (Util.IsKillingKing(rMove.to.x, rMove.to.y)) {
								KeyChineseChessActivity.imgKillKing
										.setVisibility(View.VISIBLE);
								GameParams.chessAudio
										.playRaw(GameParams.soundPromote);
								showKillingKing();
							}
							invalidate();
							//启动AI线程
							new Thread(new Runnable() {
								public void run() {
									//棋子移动数组
									int[] move = new int[4];
									GameParams.isGameStart = false;
									//开局库移动
									ChessMove startMove = Util
											.startGameLib(rMove);
									if (startMove != null) {
										bMove = startMove;
									} else {
										//移动前棋盘
										int[][] curposition = position.clone();
										// AI
										isThinking = true;
										if (isAntRule) {
											//发生了长将，避免长将
											move[0] = ruleChessMove.from.x;
											move[1] = ruleChessMove.from.y;
											move[2] = ruleChessMove.to.x;
											move[3] = ruleChessMove.to.y;
											goAI(position,
													GameParams.gameLevel, move,
													true);
											isAntRule = false;
										} else {
											goAI(position,
													GameParams.gameLevel, move,
													false);
										}
										//黑棋移动
										bMove = new ChessMove();
										bMove.from.x = move[1];
										bMove.from.y = move[0];
										bMove.to.x = move[3];
										bMove.to.y = move[2];
										bMove.chessFrom = curposition[bMove.from.x][bMove.from.y];
										bMove.chessTo = curposition[bMove.to.x][bMove.to.y];
									}
									moveStack.push(bMove);//记录移动

									rsel = false;//红棋未移动
									bsel = true;//黑棋已移动
									//计算谁获胜
									int whoIswin = Util.whoIsSuccess();
									if (whoIswin == -1) {
										//黑棋胜
										Message msg = new Message();
										msg.what = 1;
										handler.sendMessage(msg);
										GameParams.isGameStart = false;
									} else if (whoIswin == 99) {
										//和棋
										Message msg = new Message();
										msg.what = 2;
										handler.sendMessage(msg);
										GameParams.isGameStart = false;
									} else {
										//没有谁获胜
										GameParams.isGameStart = true;
										Message msg = new Message();
										msg.what = 0;
										handler.sendMessage(msg);
									}
								}
							}).start();
						} else {
							//移动不符合规则，播放棋子缩回动画
							playMoveAnimation(cX, px, cY, py);
						}
					} else if (position[cY][cX] > 7) {
						//初始选择棋子
						px = cX;
						py = cY;
						isPoint = true;
						GameParams.chessAudio.playRaw(GameParams.soundCapture);
						invalidate();
					}
				}
			}
		}
		return super.onTouchEvent(event);
	}

	//棋盘数组
	public static int position[][] = {
			{ B_CAR, B_HORSE, B_ELEPHANT, B_BISHOP, B_KING, B_BISHOP,
					B_ELEPHANT, B_HORSE, B_CAR },
			{ NOCHESS, NOCHESS, NOCHESS, NOCHESS, NOCHESS, NOCHESS, NOCHESS,
					NOCHESS, NOCHESS },
			{ NOCHESS, B_CANON, NOCHESS, NOCHESS, NOCHESS, NOCHESS, NOCHESS,
					B_CANON, NOCHESS },
			{ B_PAWN, NOCHESS, B_PAWN, NOCHESS, B_PAWN, NOCHESS, B_PAWN,
					NOCHESS, B_PAWN },
			{ NOCHESS, NOCHESS, NOCHESS, NOCHESS, NOCHESS, NOCHESS, NOCHESS,
					NOCHESS, NOCHESS },

			{ NOCHESS, NOCHESS, NOCHESS, NOCHESS, NOCHESS, NOCHESS, NOCHESS,
					NOCHESS, NOCHESS },
			{ R_PAWN, NOCHESS, R_PAWN, NOCHESS, R_PAWN, NOCHESS, R_PAWN,
					NOCHESS, R_PAWN },
			{ NOCHESS, R_CANON, NOCHESS, NOCHESS, NOCHESS, NOCHESS, NOCHESS,
					R_CANON, NOCHESS },
			{ NOCHESS, NOCHESS, NOCHESS, NOCHESS, NOCHESS, NOCHESS, NOCHESS,
					NOCHESS, NOCHESS },
			{ R_CAR, R_HORSE, R_ELEPHANT, R_BISHOP, R_KING, R_BISHOP,
					R_ELEPHANT, R_HORSE, R_CAR } };

	//View
	public KeyChineseChessView(Context context, AttributeSet attrs) {
		super(context);
		//加载所需Bitmap
		Bitmap imgBking;
		Bitmap imgBbishop;
		Bitmap imgBelephant;
		Bitmap imgBhorse;
		Bitmap imgBrook;
		Bitmap imgBcannon;
		Bitmap imgBpawn;
		Bitmap imgRking;
		Bitmap imgRbishop;
		Bitmap imgRelephant;
		Bitmap imgRhorse;
		Bitmap imgRrook;
		Bitmap imgRcannon;
		Bitmap imgRpawn;

		Bitmap imgRbg;
		Bitmap imgBbg;

		//压缩率
		scaleX = (float) screenWidth / 360;
		scaleY = (float) screenHeight / 600;
		imgBking = BitmapFactory.decodeResource(getResources(),
				R.drawable.bking_dead);
		imgBbishop = BitmapFactory.decodeResource(getResources(),
				R.drawable.bbishop_dead);
		imgBelephant = BitmapFactory.decodeResource(getResources(),
				R.drawable.belephant_dead);
		imgBhorse = BitmapFactory.decodeResource(getResources(),
				R.drawable.bhorse_dead);
		imgBrook = BitmapFactory.decodeResource(getResources(),
				R.drawable.brook_dead);
		imgBcannon = BitmapFactory.decodeResource(getResources(),
				R.drawable.bcannon_dead);
		imgBpawn = BitmapFactory.decodeResource(getResources(),
				R.drawable.bpawn_dead);

		imgRking = BitmapFactory.decodeResource(getResources(),
				R.drawable.rking_dead);
		imgRbishop = BitmapFactory.decodeResource(getResources(),
				R.drawable.rbishop_dead);
		imgRelephant = BitmapFactory.decodeResource(getResources(),
				R.drawable.relephant_dead);
		imgRhorse = BitmapFactory.decodeResource(getResources(),
				R.drawable.rhorse_dead);
		imgRrook = BitmapFactory.decodeResource(getResources(),
				R.drawable.rrook_dead);
		imgRcannon = BitmapFactory.decodeResource(getResources(),
				R.drawable.rcannon_dead);
		imgRpawn = BitmapFactory.decodeResource(getResources(),
				R.drawable.rpawn_dead);

		imgRbg = BitmapFactory.decodeResource(getResources(),
				R.drawable.rchess_bg1);
		imgBbg = BitmapFactory.decodeResource(getResources(),
				R.drawable.bchess_bg1);

		// 计算棋子半宽和半高
		chessLX = imgBking.getWidth() / 4;
		chessLY = imgBking.getHeight() / 4;
		chessLX = scaleX * chessLX;
		chessLY = scaleY * chessLY;
		matrix.postScale(scaleX * 3 / 5, scaleY * 3 / 5);
		
		//根据压缩率计算棋子等bitmap
		imgBkingNew = Bitmap.createBitmap(imgBking, 0, 0, imgBking.getWidth(),
				imgBking.getHeight(), matrix, true);
		imgBbishopNew = Bitmap.createBitmap(imgBbishop, 0, 0,
				imgBbishop.getWidth(), imgBbishop.getHeight(), matrix, true);
		imgBelephantNew = Bitmap
				.createBitmap(imgBelephant, 0, 0, imgBelephant.getWidth(),
						imgBelephant.getHeight(), matrix, true);
		imgBhorseNew = Bitmap.createBitmap(imgBhorse, 0, 0,
				imgBhorse.getWidth(), imgBhorse.getHeight(), matrix, true);
		imgBrookNew = Bitmap.createBitmap(imgBrook, 0, 0, imgBrook.getWidth(),
				imgBrook.getHeight(), matrix, true);
		imgBcannonNew = Bitmap.createBitmap(imgBcannon, 0, 0,
				imgBcannon.getWidth(), imgBcannon.getHeight(), matrix, true);
		imgBpawnNew = Bitmap.createBitmap(imgBpawn, 0, 0, imgBpawn.getWidth(),
				imgBpawn.getHeight(), matrix, true);

		imgRkingNew = Bitmap.createBitmap(imgRking, 0, 0, imgRking.getWidth(),
				imgRking.getHeight(), matrix, true);
		imgRbishopNew = Bitmap.createBitmap(imgRbishop, 0, 0,
				imgRbishop.getWidth(), imgRbishop.getHeight(), matrix, true);
		imgRelephantNew = Bitmap
				.createBitmap(imgRelephant, 0, 0, imgRelephant.getWidth(),
						imgRelephant.getHeight(), matrix, true);
		imgRhorseNew = Bitmap.createBitmap(imgRhorse, 0, 0,
				imgRhorse.getWidth(), imgRhorse.getHeight(), matrix, true);
		imgRrookNew = Bitmap.createBitmap(imgRrook, 0, 0, imgRrook.getWidth(),
				imgRrook.getHeight(), matrix, true);
		imgRcannonNew = Bitmap.createBitmap(imgRcannon, 0, 0,
				imgRcannon.getWidth(), imgRcannon.getHeight(), matrix, true);
		imgRpawnNew = Bitmap.createBitmap(imgRpawn, 0, 0, imgRpawn.getWidth(),
				imgRpawn.getHeight(), matrix, true);

		imgRbgNew = Bitmap.createBitmap(imgRbg, 0, 0, imgRbg.getWidth(),
				imgRbg.getHeight(), matrix, true);
		imgBbgNew = Bitmap.createBitmap(imgBbg, 0, 0, imgBbg.getWidth(),
				imgBbg.getHeight(), matrix, true);

		initMove();//初始化移动棋子类
		KeyChineseChessActivity.cv = this;//activity获取view实例
	}

	/**
	 * 初始化移动棋子类
	 */
	public void initMove() {
		rMove.from.x = -1;
		bMove.from.x = -1;
	}

	/**
	 * View draw
	 */
	@Override
	public void draw(Canvas canvas) {
		// TODO Auto-generated method stub
		// canvasKey = canvas;
		drawChess(canvas);
	}
	
	/**
	 * 画棋盘
	 */
	public void drawChess(Canvas canvas) {

		// 根据已动 画 移动棋子的背景
		if (rsel) {
			canvas.drawBitmap(imgRbgNew, (rMove.to.y * chessLength + chessX)
					* scaleX - imgRbgNew.getWidth() / 2, (rMove.to.x
					* chessLength + chessY)
					* scaleY - imgRbgNew.getHeight() / 2, paint);
		} else if (bsel) {
			canvas.drawBitmap(imgBbgNew, (bMove.to.y * chessLength + chessX)
					* scaleX - imgBbgNew.getWidth() / 2, (bMove.to.x
					* chessLength + chessY)
					* scaleY - imgBbgNew.getHeight() / 2, paint);
		}
		// 画棋盘
		for (int i = 0; i < 10; i++) {
			for (int j = 0; j < 9; j++) {
				if (position[i][j] == B_KING) {
					canvas.drawBitmap(imgBkingNew, (j * chessLength + chessX)
							* scaleX - imgBkingNew.getWidth() / 2, (i
							* chessLength + chessY)
							* scaleY - imgBkingNew.getHeight() / 2, paint);
				} else if (position[i][j] == B_BISHOP) {
					canvas.drawBitmap(imgBbishopNew, (j * chessLength + chessX)
							* scaleX - imgBkingNew.getWidth() / 2, (i
							* chessLength + chessY)
							* scaleY - imgBkingNew.getHeight() / 2, paint);
				} else if (position[i][j] == B_CANON) {
					canvas.drawBitmap(imgBcannonNew, (j * chessLength + chessX)
							* scaleX - imgBkingNew.getWidth() / 2, (i
							* chessLength + chessY)
							* scaleY - imgBkingNew.getHeight() / 2, paint);
				} else if (position[i][j] == B_ELEPHANT) {
					canvas.drawBitmap(
							imgBelephantNew,
							(j * chessLength + chessX) * scaleX
									- imgBkingNew.getWidth() / 2, (i
									* chessLength + chessY)
									* scaleY - imgBkingNew.getHeight() / 2,
							paint);
				} else if (position[i][j] == B_HORSE) {
					canvas.drawBitmap(imgBhorseNew, (j * chessLength + chessX)
							* scaleX - imgBkingNew.getWidth() / 2, (i
							* chessLength + chessY)
							* scaleY - imgBkingNew.getHeight() / 2, paint);
				} else if (position[i][j] == B_CAR) {
					canvas.drawBitmap(imgBrookNew, (j * chessLength + chessX)
							* scaleX - imgBkingNew.getWidth() / 2, (i
							* chessLength + chessY)
							* scaleY - imgBkingNew.getHeight() / 2, paint);
				} else if (position[i][j] == B_PAWN) {
					canvas.drawBitmap(imgBpawnNew, (j * chessLength + chessX)
							* scaleX - imgBpawnNew.getWidth() / 2, (i
							* chessLength + chessY)
							* scaleY - imgBkingNew.getHeight() / 2, paint);
				}//
				else if (position[i][j] == R_KING) {
					canvas.drawBitmap(imgRkingNew, (j * chessLength + chessX)
							* scaleX - imgBkingNew.getWidth() / 2, (i
							* chessLength + chessY)
							* scaleY - imgBkingNew.getHeight() / 2, paint);
				} else if (position[i][j] == R_BISHOP) {
					canvas.drawBitmap(imgRbishopNew, (j * chessLength + chessX)
							* scaleX - imgBkingNew.getWidth() / 2, (i
							* chessLength + chessY)
							* scaleY - imgBkingNew.getHeight() / 2, paint);
				} else if (position[i][j] == R_CANON) {
					canvas.drawBitmap(imgRcannonNew, (j * chessLength + chessX)
							* scaleX - imgBkingNew.getWidth() / 2, (i
							* chessLength + chessY)
							* scaleY - imgBkingNew.getHeight() / 2, paint);
				} else if (position[i][j] == R_ELEPHANT) {
					canvas.drawBitmap(
							imgRelephantNew,
							(j * chessLength + chessX) * scaleX
									- imgBkingNew.getWidth() / 2, (i
									* chessLength + chessY)
									* scaleY - imgBkingNew.getHeight() / 2,
							paint);
				} else if (position[i][j] == R_HORSE) {
					canvas.drawBitmap(imgRhorseNew, (j * chessLength + chessX)
							* scaleX - imgBkingNew.getWidth() / 2, (i
							* chessLength + chessY)
							* scaleY - imgBkingNew.getHeight() / 2, paint);
				} else if (position[i][j] == R_CAR) {
					canvas.drawBitmap(imgRrookNew, (j * chessLength + chessX)
							* scaleX - imgBkingNew.getWidth() / 2, (i
							* chessLength + chessY)
							* scaleY - imgBkingNew.getHeight() / 2, paint);
				} else if (position[i][j] == R_PAWN) {
					canvas.drawBitmap(imgRpawnNew, (j * chessLength + chessX)
							* scaleX - imgBpawnNew.getWidth() / 2, (i
							* chessLength + chessY)
							* scaleY - imgBkingNew.getHeight() / 2, paint);
				}
			}
		}
		// 选择棋子后，画出可移动点和选择圈
		if (isPoint) {
			//画选择圈
			Paint p = new Paint();
			p.setColor(Color.WHITE);
			p.setAlpha(125);
			p.setAntiAlias(true);
			p.setStyle(Paint.Style.STROKE);
			p.setStrokeWidth(4);
			canvas.drawCircle(px * chessLength * scaleX + chessX * scaleX, py
					* chessLength * scaleY + chessY * scaleY, chessLX
					+ (float) 3.76 * scaleX, p);
			// 画可移动点
			List<ChessPoint> list = Util.getPossibleMove(py, px);
			Paint pp = new Paint();
			pp.setColor(Color.rgb(0, 238, 118));
			pp.setAlpha(230);
			for (int m = 0; m < list.size(); m++) {
				ChessPoint cp = list.get(m);
				canvas.drawCircle(
						cp.y * chessLength * scaleX + chessX * scaleX, cp.x
								* chessLength * scaleY + chessY * scaleY, 6, pp);
			}
		}
	}

	/**
	 * 红棋移动动画
	 * 
	 * @param fx
	 * @param tx
	 * @param fy
	 * @param ty
	 */
	public void playMoveAnimation(int fx, int tx, int fy, int ty) {
		float fromX = ((float) fx - (float) 0.5) * chessLength * scaleX
				+ chessX * scaleX;
		float toX = ((float) tx - (float) 0.5) * chessLength * scaleX + chessX
				* scaleX;
		float fromY = ((float) fy - (float) 0.5) * chessLength * scaleY
				+ chessY * scaleY;
		float toY = ((float) ty - (float) 0.5) * chessLength * scaleY + chessY
				* scaleY;
		// 移动画面
		Bitmap animationBitmap = null;
		int pos = -1;
		if (isPoint) {
			pos = position[ty][tx];
		} else {
			pos = position[fy][fx];
		}
		switch (pos) {
		case R_KING:
			animationBitmap = imgRkingNew;
			break;
		case R_BISHOP:
			animationBitmap = imgRbishopNew;
			break;
		case R_ELEPHANT:
			animationBitmap = imgRelephantNew;
			break;
		case R_HORSE:
			animationBitmap = imgRhorseNew;
			break;
		case R_CAR:
			animationBitmap = imgRrookNew;
			break;
		case R_CANON:
			animationBitmap = imgRcannonNew;
			break;
		case R_PAWN:
			animationBitmap = imgRpawnNew;
			break;
		case B_KING:
			animationBitmap = imgBkingNew;
			break;
		case B_BISHOP:
			animationBitmap = imgBbishopNew;
			break;
		case B_ELEPHANT:
			animationBitmap = imgBelephantNew;
			break;
		case B_HORSE:
			animationBitmap = imgBhorseNew;
			break;
		case B_CAR:
			animationBitmap = imgBrookNew;
			break;
		case B_CANON:
			animationBitmap = imgBcannonNew;
			break;
		case B_PAWN:
			animationBitmap = imgBpawnNew;
			break;
		default:
			int asdasd = 2112;
			break;
		}
		if (animationBitmap != null) {
			KeyChineseChessActivity.runFrame(animationBitmap, fromX, toX,
					fromY, toY);
		}
	}

	/**
	 * 黑棋移动动画
	 * 
	 * @param fx
	 * @param tx
	 * @param fy
	 * @param ty
	 */
	public void playMoveAnimationB(int fx, int tx, int fy, int ty) {
		float fromX = ((float) fy - (float) 0.5) * chessLength * scaleX
				+ chessX * scaleX;
		float toX = ((float) ty - (float) 0.5) * chessLength * scaleX + chessX
				* scaleX;
		float fromY = ((float) fx - (float) 0.5) * chessLength * scaleY
				+ chessY * scaleY;
		float toY = ((float) tx - (float) 0.5) * chessLength * scaleY + chessY
				* scaleY;
		// 移动画面
		Bitmap animationBitmap = null;
		int pos = -1;
		if (isPoint) {
			pos = position[fx][fy];
		} else {
			pos = position[tx][ty];
		}
		switch (pos) {
		case R_KING:
			animationBitmap = imgRkingNew;
			break;
		case R_BISHOP:
			animationBitmap = imgRbishopNew;
			break;
		case R_ELEPHANT:
			animationBitmap = imgRelephantNew;
			break;
		case R_HORSE:
			animationBitmap = imgRhorseNew;
			break;
		case R_CAR:
			animationBitmap = imgRrookNew;
			break;
		case R_CANON:
			animationBitmap = imgRcannonNew;
			break;
		case R_PAWN:
			animationBitmap = imgRpawnNew;
			break;
		case B_KING:
			animationBitmap = imgBkingNew;
			break;
		case B_BISHOP:
			animationBitmap = imgBbishopNew;
			break;
		case B_ELEPHANT:
			animationBitmap = imgBelephantNew;
			break;
		case B_HORSE:
			animationBitmap = imgBhorseNew;
			break;
		case B_CAR:
			animationBitmap = imgBrookNew;
			break;
		case B_CANON:
			animationBitmap = imgBcannonNew;
			break;
		case B_PAWN:
			animationBitmap = imgBpawnNew;
			break;
		default:
			break;
		}
		if (animationBitmap != null) {
			KeyChineseChessActivity.runFrame(animationBitmap, fromX, toX,
					fromY, toY);
		}
	}

	// JNI (AI)
	public native void goAI(int position[][], int level, int move[],
			boolean isAgainstRule);

	static {
		System.loadLibrary("KeyChineseChessAI");
	}

	//handler
	public Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			//棋子移动
			case 0:
				if (Util.isEatChess(bMove)) {
					GameParams.chessAudio.playRaw(GameParams.soundEat);
				} else {
					GameParams.chessAudio.playRaw(GameParams.soundMove);
				}
				invalidate();
				//播放黑棋移动动画
				playMoveAnimationB(bMove.from.x, bMove.to.x, bMove.from.y,
						bMove.to.y);
				// 将军
				if (Util.IsKillingKing(bMove.to.x, bMove.to.y)) {
					KeyChineseChessActivity.imgKillKing
							.setVisibility(View.VISIBLE);
					GameParams.chessAudio.playRaw(GameParams.soundPromote);
					//记录可能违反规则的移动
					keyChineseChessRule.checkIsKillUtil(position);
					if (keyChineseChessRule.listPosition.size() <= 4) {
						ruleChessMove.from.x = bMove.from.x;
						ruleChessMove.from.y = bMove.from.y;
						ruleChessMove.to.x = bMove.to.x;
						ruleChessMove.to.y = bMove.to.y;
						ruleChessMove.chessFrom = bMove.chessFrom;
						ruleChessMove.chessTo = bMove.chessTo;
					}
					showKillingKing();
				} else {
					//如果规则符合，清空违反规则记录
					keyChineseChessRule.listPosition.clear();
				}
				isThinking = false;
				break;
			case 1:
				//黑棋胜，显示失败
				KeyChineseChessActivity.imgVBlackLive
						.setVisibility(View.VISIBLE);
				GameParams.chessAudio.playRaw(GameParams.soundLoss);
				invalidate();
				playMoveAnimationB(bMove.from.x, bMove.to.x, bMove.from.y,
						bMove.to.y);
				caculateLoseChess();//计算输棋分
				exitGameBoard();
				break;
			case 2:
				//和棋,显示和棋
				KeyChineseChessActivity.imgVAllLive.setVisibility(View.VISIBLE);
				invalidate();
				playMoveAnimationB(bMove.from.x, bMove.to.x, bMove.from.y,
						bMove.to.y);
				exitGameBoard();
				break;
			case 3:
				//将军显示消失
				KeyChineseChessActivity.imgKillKing.setVisibility(View.GONE);
				break;
			case 4:
				if (GameParams.activity != null) {
					GameParams.activity.finish();
				}
				break;
			default:
				break;
			}
		}
	};

	/**
	 * 显示将军
	 */
	public void showKillingKing() {
		Timer timer = new Timer();
		TimerTask timerTask = new TimerTask() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				Message msg = new Message();
				msg.what = 3;
				handler.sendMessage(msg);
			}
		};
		timer.schedule(timerTask, 1000);
	}

	/**
	 * 2秒后退出
	 */
	public void exitGameBoard() {
		Timer timer = new Timer();
		TimerTask timerTask = new TimerTask() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				Message msg = new Message();
				msg.what = 4;
				handler.sendMessage(msg);
			}
		};
		timer.schedule(timerTask, 2000);
	}

	/**
	 * 初始化常量
	 */
	public void initContants() {
		isPoint = false;
		px = -99;
		py = -99;
		rsel = false;
		bsel = false;
		for (int i = 0; i < 10; i++) {
			for (int j = 0; j < 9; j++) {
				position[i][j] = NOCHESS;
			}
		}
		position[0][0] = B_CAR;
		position[0][1] = B_HORSE;
		position[0][2] = B_ELEPHANT;
		position[0][3] = B_BISHOP;
		position[0][4] = B_KING;
		position[0][5] = B_BISHOP;
		position[0][6] = B_ELEPHANT;
		position[0][7] = B_HORSE;
		position[0][8] = B_CAR;

		position[2][1] = B_CANON;
		position[2][7] = B_CANON;

		position[3][0] = B_PAWN;
		position[3][2] = B_PAWN;
		position[3][4] = B_PAWN;
		position[3][6] = B_PAWN;
		position[3][8] = B_PAWN;

		position[9][0] = R_CAR;
		position[9][1] = R_HORSE;
		position[9][2] = R_ELEPHANT;
		position[9][3] = R_BISHOP;
		position[9][4] = R_KING;
		position[9][5] = R_BISHOP;
		position[9][6] = R_ELEPHANT;
		position[9][7] = R_HORSE;
		position[9][8] = R_CAR;

		position[7][1] = R_CANON;
		position[7][7] = R_CANON;

		position[6][0] = R_PAWN;
		position[6][2] = R_PAWN;
		position[6][4] = R_PAWN;
		position[6][6] = R_PAWN;
		position[6][8] = R_PAWN;
		moveStack.clear();
	}

	/**
	 * 计算获胜分
	 * @return
	 */
	private boolean caculateWinScore() {
		int winScore = GameParams.gameLevel;
		if (UserSystemData.UserInfo.addScore(winScore)) {
			if (UserSystemData.UserInfo.write() == true) {
				int rank = UserSystemData.UserInfo.getUserRank();
				if (GameParams.gameLevel >= rank) {
					rank++;
					UserSystemData.UserInfo.getUserInfo().setUserRank(rank);
				}
				return true;
			}
		}
		return false;
	}

	/**
	 * 计算失败分
	 */
	private void caculateLoseChess() {
		if (UserSystemData.UserInfo.inviteChess(KeyScore.subScoreIflose) >= 0) {
			if (UserSystemData.UserInfo.write() == true) {
				;
			}
		}
	}
	
	/**
	 * 清空可能违反规则的记录
	 */
	public void refreshRuleListPosition()
	{
		keyChineseChessRule.listPosition.clear();
	}
}
